package com.augurit.wf.jbpmex.cmd;

import org.jbpm.api.TaskService;
import org.jbpm.api.cmd.Environment;
import org.jbpm.pvm.internal.cmd.AbstractCommand;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;
import org.jbpm.pvm.internal.session.DbSession;
import org.jbpm.pvm.internal.task.TaskImpl;

import com.augurit.wf.common.dao.Jbpm4HistTaskDao;
import com.augurit.wf.common.entity.Jbpm4HistTask;

public class TakeBackTaskCmd extends AbstractCommand<Void>{

	private static final long serialVersionUID = -4993984682747433400L;
	
	private String taskId;
	private String hisTaskId;
	
	private String type;
	public TakeBackTaskCmd(String taskId ,String hisTaskId,String type){
		this.taskId = taskId;
		this.hisTaskId = hisTaskId;
		this.type = type;
	}
	
	/**
	 * 舒军修改 11年2月20日
	 */
	public Void execute(Environment environment) throws Exception {
		DbSession session = environment.get(DbSession.class);
		
		TaskImpl task = session.get(TaskImpl.class, Long.valueOf(taskId));
		
		Jbpm4HistTaskDao dao = environment.get(Jbpm4HistTaskDao.class);
		Jbpm4HistTask jbpm4HistTask = dao.get(Long.parseLong(hisTaskId));
		
		
		ExecutionImpl execution = task.getExecution();
		ActivityImpl activity = (ActivityImpl)execution.getActivity();
		
		String destActivityName = jbpm4HistTask.getActivityName();
		//若是回退，直接执行；若是取回，该任务没有签收,则可以取回
		if(type.equals("1") ||(type.equals("0") && task.getSignTime() == null)){
			
			//建立转向
			CreateTransitionCmd cmd =  new CreateTransitionCmd(execution.getId(),destActivityName);
			cmd.execute(environment);
			
			String newTrainsitionName = "to "+ destActivityName;
			
			//流转
			TaskService taskService = environment.get(TaskService.class);
			taskService.completeTask(task.getId(),newTrainsitionName);
			
			//删除建立的转向
			deletTransition(activity,newTrainsitionName);
		}
		return null;
	}
	
	public void deletTransition(ActivityImpl activity,String trainsitionName){
		if(activity != null){
			
			//获取新建立的转向
			TransitionImpl transition = (TransitionImpl)activity.findOutgoingTransition(
					trainsitionName);
			
			//删除建立的转向
			activity.removeOutgoingTransition(transition);
		}
	}
	


}
